package com.ygqh.baby.service.erp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ygqh.baby.ao.ResponseEntity;
import com.ygqh.baby.exception.YgHttpException;
import com.ygqh.baby.http.YgRequestExecutor;
import com.ygqh.baby.http.YgResponse;
import com.ygqh.baby.po.YgOrder;
import com.ygqh.baby.po.YgProduct;
import com.ygqh.baby.utils.ExceptionUtil;

@Component
public class ErpApi {
	protected Logger logger = Logger.getLogger(this.getClass());

	protected final YgRequestExecutor ygRequestExecutor;

	private static String ERP_SERVER_URL = "http://192.168.1.80:8282/gateway";

	public ErpApi() {
		super();
		this.ygRequestExecutor = new YgRequestExecutor();
	}
	private ResponseEntity doRequest(Map<String, String> data, String method) {
		ResponseEntity msg = null;
		try {
			data.put("method", method);
			YgResponse response = ygRequestExecutor.post(ERP_SERVER_URL, data);
			msg = response.getAsObject(new TypeReference<ResponseEntity>() {
			});
		} catch (YgHttpException e) {
			logger.error("method=" + method + ";" + ExceptionUtil.getExceptionMsg(e)); 
			ResponseEntity.error(ExceptionUtil.getExceptionMsg(e));
			e.printStackTrace();
		}
		return msg;
	}

	public ResponseEntity orderPush(List<YgOrder> orderList) {
		String method = "order.push";
		Map<String, String> data = new HashMap<String, String>();
		data.put("orderList", JSON.toJSONString(orderList));
		return this.doRequest(data, method);
	}

	public ResponseEntity productPush(List<YgProduct> productList) {
		if (CollectionUtils.isEmpty(productList)) {
			return ResponseEntity.error("商品集合为空");
		}
		String method = "product.push";
		Map<String, String> data = new HashMap<String, String>();
		data.put("productList", JSON.toJSONString(productList));
		return this.doRequest(data, method);
	}

	public ResponseEntity productPush(YgProduct product) {
		String method = "product.push";
		Map<String, String> data = new HashMap<String, String>();
		List<YgProduct> list = new ArrayList<>();
		list.add(product);
		data.put("productList", JSON.toJSONString(list));
		return this.doRequest(data, method);
	}
}
